#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/9/19 10:17
# @Author  : youfeng
import json
import sys

import demjson as demjson
import redis

from config.redis_conf import RedisDataCacheConfig
from ext.redis_key_wrap import RedisKeyWrap

# reload(sys)
#
# sys.setdefaultencoding('utf8')


class RedisResultHandler(object):
    __EXPIRE_TIME = 24 * 3600 * 7

    def __init__(self, log):
        self.log = log

        self.__redis_client = redis.StrictRedis(host=RedisDataCacheConfig.HOST,
                                                port=RedisDataCacheConfig.PORT,
                                                password=RedisDataCacheConfig.PASSWORD,
                                                db=RedisDataCacheConfig.DB,
                                                max_connections=RedisDataCacheConfig.MAX_CONNECTIONS)

    # 存储结果数据到redis
    def save(self, company, result_dict):
        key = RedisKeyWrap.get_gsxt_result_key(company)
        try:
            json_data_str = json.dumps(result_dict)
            json_dict = json.loads(json_data_str)
            json_str = demjson.encode(json_dict)
            self.__redis_client.setex(key, self.__EXPIRE_TIME, json_str)
            return True
        except Exception as e:
            self.log.error("存储redis异常: company = {}".format(company))
            self.log.exception(e)

        return False
